package com.snake.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.foxinmy.weixin4j.api.MchApi;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.WeixinPayAccount;
import com.foxinmy.weixin4j.payment.mch.Redpacket;
import com.foxinmy.weixin4j.payment.mch.RedpacketSendResult;
import com.foxinmy.weixin4j.sign.WeixinPaymentSignature;
import com.foxinmy.weixin4j.xml.XmlStream;

public class MyCashApi extends MchApi {

	public MyCashApi(WeixinPayAccount weixinAccount) {
		super(weixinAccount);
		// TODO Auto-generated constructor stub
	}
	
	public RedpacketSendResult sendRedpack(Redpacket redpacket,String mchId,String wxappid,String paySignKey)
			throws WeixinException {
		super.declareMerchant(redpacket);
		JSONObject obj = (JSONObject) JSON.toJSON(redpacket);
		obj.put("wxappid", wxappid);
		obj.put("mch_id", mchId);
		obj.remove("appid");
		WeixinPaymentSignature weixinPaymentSignature=new WeixinPaymentSignature(paySignKey);
		obj.put("sign", weixinPaymentSignature.sign(obj));
		String param = XmlStream.map2xml(obj);
		WeixinResponse response = getWeixinSSLExecutor()
				.post(redpacket.getTotalNum() > 1 ? getRequestUri("groupredpack_send_uri")
						: getRequestUri("redpack_send_uri"), param);
		String text = response.getAsString()
				.replaceFirst("<wxappid>", "<appid>")
				.replaceFirst("</wxappid>", "</appid>");
		String[] textSplit = text.split("</xml>");
		String formatDate = DateUtil.formatDate(new Date(),
				"yyyy-MM-dd HH:mm:ss");
		text=textSplit[0]+"<send_time><![CDATA["+formatDate+"]]></send_time></xml>";
		return XmlStream.fromXML(text, RedpacketSendResult.class);
	}
	
}
